﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MongoServices.Example.Services;
using MongoServices.Example.Models.DomainModels;
using MongoDB.Bson;
using MongoServices.Example.Models.ViewModels;
using AutoMapper;

namespace MongoServices.Example.Controllers
{
	[OutputCache(Duration=0,VaryByParam="*")]
    public class BlogController : Controller
    {
		protected IBlogPostService BlogPostService { get; private set; }
		protected IBlogPostShortService BlogPostShortService { get; private set; }

		public BlogController(IBlogPostService blogPostService, IBlogPostShortService blogPostShortService)
		{
			BlogPostService = blogPostService;
			BlogPostShortService = blogPostShortService;
		}

        public ViewResult Index()
        {
			return View(new BlogIndexViewModel {
				Items = Mapper.Map<IEnumerable<BlogPostShort>, IEnumerable<BlogIndexItemViewModel>>(BlogPostService.GetAll())
			});
		}

		[HttpGet]
		public ViewResult Post(ObjectId id)
		{
			return View(Mapper.Map<BlogPost, BlogPostDetailViewModel>(BlogPostService.GetById(id)));

		}

		[HttpGet]
		public ViewResult Create()
		{
			return View(new BlogCreateEditViewModel());
		}

		[HttpPost]
		public ActionResult Create(BlogCreateEditViewModel model)
		{
			if (ModelState.IsValid)
			{
				BlogPostService.Save(Mapper.Map<BlogCreateEditViewModel, BlogPost>(model));
				return RedirectToAction("Index");
			}
			else
			{
				return View(model);
			}
		}

		[HttpGet]
		public ViewResult Edit(ObjectId id)
		{
			var model = Mapper.Map<BlogPost, BlogCreateEditViewModel>(BlogPostService.GetById(id));

			model.ReturnUrl = Request.UrlReferrer.PathAndQuery;

			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(BlogCreateEditViewModel model)
		{
			if (ModelState.IsValid)
			{
				BlogPostService.Save(Mapper.Map<BlogCreateEditViewModel, BlogPost>(model, BlogPostService.GetById(model.Id)));
				return Redirect(model.ReturnUrl);
			}
			else
			{
				return View(model);
			}
		}

		public ActionResult Delete(ObjectId id)
		{
			BlogPostService.DeleteById(id);
			return RedirectToAction("Index");
		}

		public ActionResult GenerateSamples()
		{
			BlogPostService.GenerateSamplePosts(20);
			return RedirectToAction("Index");
		}
    }
}
